<template>
  <div>
    <div class="media-upload__local-url" v-if="file">
      <span class="mr5">{{ file }}</span>
      <i class="el-icon-delete el-button--text poi" @click.stop="handleDelete" />
    </div>
    <el-upload
      v-else
      action=""
      :accept="accept"
      class="el-upload__drag--fit"
      drag
      :http-request="httpRequest"
      :show-file-list="false"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        <div style="line-height: 1em;">将文件拖到此处，或<em>点击上传</em></div>
        <div style="line-height: 1em;" class="el-upload__tip" slot="tip">
          {{ tip }}
        </div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { postStaticresourceUpload } from "@/apis/paas/StaticResourceController.js";
import { FormItem, Upload, Button, Input } from "element-ui";

export default {
  name: "MediaUpload",

  components: {
    [FormItem.name]: FormItem,
    [Upload.name]: Upload,
    [Button.name]: Button,
    [Input.name]: Input,
  },

  props: {
    accept: {
      type: String,
      default: ".mp4",
    },
    size: {
      type: Number,
      default: 100,
    },
    tip: {
      type: String,
      default: "只能上传mp4文件，且不超过100MB",
    },
    file: {
      type: String,
      default: "",
    },
  },

  computed: {
    fileList() {
      return this.file ? [this.file] : [];
    },
  },

  methods: {
    async httpRequest(param) {
      const file = param.file;
      const fileSize = file.size / 1024 / 1024;
      const isLt = fileSize < this.size;
      if (!isLt) {
        this.$message.error(`大小不能超过${this.size}MB`);
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      const res = await postStaticresourceUpload(formData);
      console.log(res);
      this.$emit("update:file", res);
    },

    handleDelete() {
      this.$emit("update:file", "");
    },
  },
};
</script>

<style lang="scss">
.el-upload__drag--fit {
  .el-upload {
    display: block;
  }

  .el-upload-dragger {
    width: auto;
  }
}

.media-upload{
  &__local-url{
    line-height: 20px;
    word-break: break-all;
    color: #666;
  }
}
</style>
